﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DbMapper.view;
using DbMapper.controller;
using DbMapper.model;

namespace DbMapper {
    public partial class DataGroup : UserControl {
        LoginWindow loginWindow = new LoginWindow();
        DataGroupController dataGroupController = new DataGroupController();
        public Table Table { get { return new Table(this.DbComboBox.Text); } }
        //public Field Field { get { return new Field(DbListView.SelectedIndices[0], DbListView.SelectedItems.ToString()); } }
        public Field Field { get { return new Field(0, "TestName2"); } }
        public DbInfo DbInfo {
            get {
                return new DbInfo(loginWindow.Host, loginWindow.User, loginWindow.Password, loginWindow.Database);
            }
        }

        public DataGroup() {
            InitializeComponent();
        }

        public void loginDbButton_Click(object sender, EventArgs e) {
            //如果按钮是退出，点击按钮，清空下拉列表和下拉选项，
            if (this.loginDbButton.Text == "退出") {
                this.DbComboBox.Items.Clear();
                this.DbListView.Items.Clear();
                this.loginDbButton.Text = "登录";
                this.DbName.Text = "";

            }

            //如果是登录，点击按钮，弹出登录框
            else {

                var result = loginWindow.ShowDialog();
                if (this.DbComboBox.Text != "") {
                    this.DbComboBox.Items.Clear();
                    this.DbListView.Items.Clear();
                    //DialogResult result = loginWindow.ShowDialog();
                    result = loginWindow.ShowDialog();
                }

                if (result == DialogResult.OK) {
                    dataGroupController.UpdateDatabase(new DbInfo(loginWindow.Host, loginWindow.User, loginWindow.Password, loginWindow.Database));
                    UpdateTables();
                    this.DbName.Text = loginWindow.Database;
                    this.loginDbButton.Text = "退出";
                }
            }
        }

        public void UpdateTables() {
            var reader = dataGroupController.GetTableName();
            while (reader.Read()) {
                DbComboBox.Items.Add(reader[0]);
            }
        }

        public void DbComboBox_SelectedIndexChanged(object sender, EventArgs e) {
            UpDateFieldName(dataGroupController.dataGroupViewModel.DbInfo);
        }

        public void UpDateFieldName(DbInfo dbInfo) {
            this.DbListView.Items.Clear();
            string name = this.DbComboBox.Text.Trim();
            var reader = dataGroupController.GetTableField(name);
            while (reader.Read()) {
                DbListView.Items.Add((reader[0]).ToString());
            }
        }

        public void DbListView_SelectedIndexChanged(object sender, EventArgs e) {
        }


    }
}
